package sync;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 描述:多线程（生产者消费者模型）（synchronized）
 *
 * @author
 * @created 2022/1/10 19:57
 */
public class ProducerConsumer {

    public static final int CAPACITY = 5;

    public static void main(String[] args) {
        LinkedBlockingDeque<Integer> queue = new LinkedBlockingDeque<>();
        Producer producer1 = new Producer(queue, CAPACITY);
        Producer producer2 = new Producer(queue, CAPACITY);
        Consumer consumer1 = new Consumer(queue, CAPACITY);
        Consumer consumer2 = new Consumer(queue, CAPACITY);
        Consumer consumer3 = new Consumer(queue, CAPACITY);
        producer1.start();
        producer2.start();
        consumer1.start();
        consumer2.start();
        consumer3.start();
    }

}

/*生产者*/
class Producer extends Thread {
    private Queue<Integer> queue;
    private int maxSize;
    int i = 0;

    public Producer(Queue<Integer> queue, int maxSize) {
        this.queue = queue;
        this.maxSize = maxSize;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (queue) {
                while (queue.size() >= maxSize) {
                    try{
                        queue.wait();
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
                queue.offer(i++);
                queue.notifyAll();
                try{
                    Thread.sleep(1000);
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class Consumer extends Thread {
    private Queue<Integer> queue;
    int maxSize;

    public Consumer(Queue<Integer> queue, int maxSize) {
        this.queue = queue;
        this.maxSize = maxSize;
    }

    @Override
    public void run() {
        while (queue.isEmpty()) {
            synchronized (queue) {
                try{
                    queue.wait();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
            queue.poll();
            queue.notifyAll();
        }
    }
}
